object RecursiveFunctionDemo extends App {
  def factorial(n: Int): Int = {
    if (n <= 1) 1
    else n * factorial(n - 1)
  }
  def sortScores(scores: List[Int]): List[Int] = {
    if (scores.length <= 1) scores
    else {
      val pivot = scores.head
      val (lessOrEqual, greater) = scores.tail.partition(_ <= pivot)
      sortScores(lessOrEqual) ::: List(pivot) ::: sortScores(greater)
    }
  }
  def calculateRanks(scores: List[Int], sortedScores: List[Int] = Nil): List[Int] = {
    if (scores.isEmpty) Nil
    else {
      val currentScore = scores.head
      val sorted = if (sortedScores.isEmpty) sortScores(scores).reverse else sortedScores
      val rank = sorted.indexOf(currentScore) + 1
      rank :: calculateRanks(scores.tail, sorted)
    }
  }
  println("阶乘计算: ")
  println(s"5的阶乘是: ${factorial(5)}")  // 输出120

  val mathScores = List(85, 92, 76, 88, 90, 76, 85, 92)
  println(s"\n原始成绩: $mathScores")

  val sorted = sortScores(mathScores)
  println(s"排序后(升序): $sorted")

  val ranks = calculateRanks(mathScores)
  println(s"对应名次: $ranks")
  case class Student(name: String, score: Int)
  val students = List(
    Student("张三", 85),
    Student("李四", 92),
    Student("王五", 76),
    Student("赵六", 88)
  )

  // 递归函数: 查找最高分学生（改为纯递归实现，移除非递归的max/filter）
  def findTopStudents(students: List[Student]): List[Student] = {
    def findMaxScore(list: List[Student], currentMax: Int): Int = {
      if (list.isEmpty) currentMax
      else findMaxScore(list.tail, math.max(currentMax, list.head.score))
    }

    def filterByScore(list: List[Student], score: Int): List[Student] = {
      if (list.isEmpty) Nil
      else if (list.head.score == score) list.head :: filterByScore(list.tail, score)
      else filterByScore(list.tail, score)
    }

    if (students.isEmpty) Nil
    else {
      val topScore = findMaxScore(students.tail, students.head.score)
      filterByScore(students, topScore)
    }
  }

  val topStudents = findTopStudents(students)
  println(s"\n最高分学生: ${topStudents.map(_.name).mkString(", ")}，分数: ${topStudents.head.score}")
}